package com.mayikt.swagger.filter;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Name MayiktGatewayFilter
 * @Author 枫火
 * @Date 2021/5/21 11:04
 * @Description
 **/
@Component
public class MayiktGatewayFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //  nginx 会从请求头中设置 客户端的真实ip放入网关
//        String sourceIp = exchange.getRequest().getHeaders().getFirst("X-Real-IP");
//        if (StringUtils.isEmpty(sourceIp)) {
//            ServerHttpResponse response = exchange.getResponse();
//            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("code", "500");
//            jsonObject.put("msg", "sourceIp is null");
//            DataBuffer buffer = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
//            return response.writeWith(Mono.just(buffer));
//        }
        // 网关放行 转发到真实服务
        return chain.filter(exchange);
    }

}

